import routerLink from './routerLink.vue';
let _Vue = null;

export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;
    _Vue = Vue;
    Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      },
    });
  }
  constructor(options) {
    this.options = options;
    this.routerMap = {};
    this.data = _Vue.observable({
      current: '/',
    });
  }

  init() {
    this.createRouteMap();
    this.initComponents(_Vue);
    this.initEvent();
  }

  createRouteMap() {
    for (const route of this.options.routes) {
      this.routerMap[route.path] = route.component;
    }
  }

  initComponents(Vue) {
    const self = this;
    Vue.component('router-link', routerLink);
    Vue.component('router-view', {
      render(h) {
        return h(self.routerMap[self.data.current]);
      },
    });
  }

  initEvent() {
    if (this.options.mode === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    } else {
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash.substring(1);
      });
    }
  }
}
